package com.jucai.pppeiyouclient.base;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.View;

import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jucai.pppeiyouclient.utils.ActivityCollector;
import com.jucai.pppeiyouclient.utils.LogUtils;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Mars-SC on 2017/5/21.
 */

public abstract class BaseTakePhotoActivity extends TakePhotoActivity implements View.OnClickListener {
    private static final int SEND_PERMISSION_REQUEST = 6001;//避免和 tokePhoto 插件冲突
    private static PermissionListener mListener;
    AlertDialog alertDialog;
    private boolean isShowPermissionDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //添加到列表中
        ActivityCollector.addActivity(this);
        initView(savedInstanceState);
        try {
            initData();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        setListener();
        configCompress(getTakePhoto());
        configTakePhotoOption(getTakePhoto());
    }

    /**
     * 压缩
     *
     * @param takePhoto
     */
    protected void configCompress(TakePhoto takePhoto) {

        int maxSize = 1 * 1024 * 1024;
        int width = 800;
        int height = 800;
        boolean showProgressBar = true;
        boolean enableRawFile = true;//保留原图
        CompressConfig config = new CompressConfig.Builder()
                .setMaxSize(maxSize)
                .setMaxPixel(width >= height ? width : height)
                .enableReserveRaw(enableRawFile)
                .create();
        LogUtils.e("photo = " + showProgressBar);
        takePhoto.onEnableCompress(config, showProgressBar);
    }

    /**
     * 使用take 相册
     *
     * @param takePhoto
     */
    private void configTakePhotoOption(TakePhoto takePhoto) {
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(true);
        takePhoto.setTakePhotoOptions(builder.create());

    }


    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
    }




    @Override
    protected void onResume() {
        super.onResume();
        loadNetData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //从列表移除
        ActivityCollector.removeActivity(this);
    }

    protected abstract void initView(Bundle savedInstanceState);

    protected abstract void initData() throws ParseException;

    protected abstract void loadNetData();

    protected abstract void setListener();


    public void onRuntimePermissionRequest(String[] permissions, PermissionListener listener) {
        Activity top = ActivityCollector.getTopActivity();
        List<String> deniedPermissions = new ArrayList<>();//存储被拒绝的权限
        mListener = listener;

        if (top == null) {
            return;
        } else {
            for (String p : permissions) {
                if (ContextCompat.checkSelfPermission(top, p) != PackageManager.PERMISSION_GRANTED) {
                    deniedPermissions.add(p);
                }
            }
            if (deniedPermissions.isEmpty()) {
                listener.onGranted();
            } else {
                ActivityCompat.requestPermissions(top,
                        deniedPermissions.toArray(new String[deniedPermissions.size()]), SEND_PERMISSION_REQUEST);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case SEND_PERMISSION_REQUEST:
                List<String> deniedPermissionList = new ArrayList<>();
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                            deniedPermissionList.add(permissions[i]);
                        }
                        if (!ActivityCompat.shouldShowRequestPermissionRationale(BaseTakePhotoActivity.this, permissions[i])) {
                            isShowPermissionDialog = true;
                        }
                    }
                    if (deniedPermissionList.isEmpty()) {
                        //权限全部同意处理
                        mListener.onGranted();
                        isShowPermissionDialog = false;
                    } else {
                        //存在拒绝权限处理
                        mListener.onDenied(deniedPermissionList);

                        if (isShowPermissionDialog) {
                            if (alertDialog == null) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(BaseTakePhotoActivity.this).setMessage("拍照或选择照片需要读取摄像头和SD卡存储")
                                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                            }
                                        }).setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                                                startActivity(intent);
                                            }
                                        });
                                alertDialog = builder.create();
                            }
                            alertDialog.show();
                        }
                    }
                }
                break;
            default:
                break;
        }
    }
}
